<template>
	<view class="task-bg">
		<uv-navbar
			title="任务"
			placeholder
			:auto-back="false"
			bg-color="transparent"
      left-icon=""
			title-style="color: #000000; font-size: 32rpx"
		/>
		<view class="fixbox">
			<view v-if="state.offlineMode" class="offline-map" :style="{ height: windowHeight + 'px', width: '100%' }">离线模式</view>
			<map
				v-else
				:latitude="state.centerLat"
				:longitude="state.centerLng"
				:scale="state.mapScale"
				:markers="state.isReloadMap ? state.markers : []"
				:style="{ height: windowHeight + 'px', width: '100%' }"
			/>
			<scroll-view style="height: 56vh" scroll-y :scroll-top="0" @scrolltolower="scrolltolower">
				<view class="list ss-flex ss-row-left ss-r-20 ss-shadow" v-for="(i, index) in dataList" :key="index"
					@click="handleDetail(i.subPlanId, i.projectName, i.cycleNo)">
					<view class="list_l" :style="{
							backgroundColor: getStatusColor(i.status),
							height: i.status == 4 ? '330rpx' : '250rpx',
						}">
					</view>
					<view class="ss-grey-2 ss-w-100 ss-font-24">
						<view class="ss-m-x-20">
							<view class="ss-m-y-14 ss-font-28 ss-black">
								{{ i.projectName }} ( 第{{ i.cycleNo }}期 ）
							</view>
							<view class="ss-m-y-10 ss-flex">
								{{ i.beginTime }}
								<view class="mes ss-m-x-20">{{ i.remark }}</view>
							</view>
							<view class="ss-m-y-14 ss-flex">
								总体：
								<uv-line-progress :percentage="i.projectRate" :activeColor="getStatusColor(i.status)" />
							</view>
							<view class="ss-m-y-14 ss-flex">
								本月：
								<uv-line-progress :percentage="i.subPlantRate"
									:activeColor="getStatusColor(i.status)" />
							</view>
							<view class="ss-m-y-14">
								<uv-icon :name="getStatusIcon(i.status)" :label="getStatusLabel(i.status)" size="16"
									labelSize="12" />
							</view>
						</view>
						<view class="list_line ss-font-26" v-if="i.status == 4 && i.projectLeader" @tap.stop="toReport(i.subPlanId)">
							生成报告
						</view>
					</view>
				</view>
				<uv-load-more v-if="dataList.length > 0" :status="status" line />
				<uv-empty v-else margin-top="20vh" :icon="empty" text="暂无任务" />
			</scroll-view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		nextTick,
		watch,
		onBeforeUnmount,
	} from "vue";
	import { calculateMapBounds } from "@/common/mothed.js";
	import { checkNetwork } from "@/request/common.js";
	import {
		taskList,
		generateReport
	} from "@/request/task.js";
	import empty from "@/static/empty.png";
	import iconGreen from "@/static/sign/green.png";
	import iconRed from "@/static/sign/red.png";
	import iconClock from "@/static/home/icon_clock.png";
	import iconSuccess from "@/static/home/icon_success.png";
	import iconProgress from "@/static/home/icon_progress.png";
	import iconWarn from "@/static/home/icon_warn.png";

	const props = defineProps({
		// 是否下拉刷新
		refresh: {
			type: Boolean,
			default: false,
		},
		// 上拉加载
		onMore: {
			type: Boolean,
			default: false,
		},
	});

	const emit = defineEmits(["update:refresh", "update:onMore", "count"]);

	const total = ref(0); // 总条数
	const queryParams = reactive({
		pageNum: 1, // 页码
		pageSize: 10, // 条数
	});
	const dataList = ref([]); // 数据列表
	const status = ref("loadmore"); // 加载状态
	const state = reactive({
		latitude: 0, // 定位纬度
		longitude: 0, // 定位经度
		markers: [], // 地图标记列表
		isReloadMap: true, // 是否刷新地图
		offlineMode: false,
		offlineId: "", // 离线任务id
		mapScale: 16, // 地图缩放比例
		centerLat: 0, // 缩放中心点纬度
		centerLng: 0, // 缩放中心点经度
	});

	// 获取高度
	const windowHeight = computed(() => {
		var systemInfo = uni.getSystemInfoSync();
		return systemInfo.windowHeight / 3.8;
	});

	watch(
		props,
		(v) => {
			if (v?.refresh) {
				setTimeout(() => {
					queryParams.pageNum = 1;
					getList();
				}, 0);
			}
			if (v?.onMore) {
				if (total.value > dataList.value.length) {
					queryParams.pageNum += 1;
					getList();
				}
			}
		}, {
			immediate: true,
			deep: true,
		}
	);

	onMounted(() => {
		getLocationInfo();
		// #ifdef H5
		getList();
		// #endif
		uni.$on("taskReport", () => {
			getList();
		});
		uni.$on("listStateTask", () => {
			getList();
		});
		uni.$on("network-change", (status) => {
			if (status == "none") {
				state.offlineMode = true;
				let offline = uni.getStorageSync('offline-task-list');
				dataList.value = offline.data || [];
				state.offlineId = offline.subPlanId;
			} else {
				state.offlineMode = false;
				getLocationInfo();
			}
		});
		// #ifdef APP-PLUS
		// 禁止下拉刷新
		const pages = getCurrentPages();  
		const page = pages[pages.length - 1];  
		const currentWebview = page.$getAppWebview();
		currentWebview.setStyle({  
			pullToRefresh: {  
				support: false,
				style: plus.os.name === 'Android' ? 'circle' : 'default'
			}  
		});
		uni.stopPullDownRefresh();
		// #endif
	});

	onBeforeUnmount(() => {
		uni.$off("taskReport");
		uni.$off("listStateTask");
	});

	// 刷新地图
	const reloadMap = async () => {
		let includePoints = state.markers.map((item) => {
			return [item.longitude, item.latitude];
		});
		const points = [...includePoints, [state.longitude, state.latitude]];
		const res = await calculateMapBounds(points);
		state.mapScale = res.scale;
		state.centerLng = res.centerLng;
		state.centerLat = res.centerLat;
		state.isReloadMap = false;
		nextTick(() => {
			state.isReloadMap = true;
		});
	};

	// 获取图标文字
	const getStatusLabel = (e) => {
		switch (e) {
			case 2:
				return "未开始";
			case 3:
				return "进行中";
			case 4:
				return "已完成";
			case 5:
				return "已超时";
			default:
				return "";
		}
	};

	// 获取图标样式
	const getStatusIcon = (e) => {
		switch (e) {
			case 2:
				return iconClock;
			case 3:
				return iconProgress;
			case 4:
				return iconSuccess;
			case 5:
				return iconWarn;
			default:
				return "";
		}
	};

	// 获取图标颜色
	const getStatusColor = (e) => {
		switch (e) {
			case 2:
				return "#F2CE90";
			case 3:
				return "#87BCF5";
			case 4:
				return "#85C889";
			case 5:
				return "#F2AFA5";
			default:
				return "";
		}
	};

	// 获取当前定位
	const getLocationInfo = async () => {
		const network = await checkNetwork(); // 检查网络
		if (network == "none") {
			state.offlineMode = true;
			let offline = uni.getStorageSync('offline-task-list');
			if (offline) {
        dataList.value = offline.data || [];
        state.offlineId = offline.subPlanId;
      }
			return;
		} else {
			state.offlineMode = false;
		}
		uni.getLocation({
			type: "gcj02",
			success: async (res) => {
				state.latitude = res.latitude;
				state.longitude = res.longitude;
        getList();
			},
			fail: (e) => {
				console.log("获取位置失败：", e);
				setTimeout(() => {
					getLocationInfo();
				}, 1000);
			}
		});
	};

  // 滚动加载
	const scrolltolower = () => {
		if (total.value > dataList.value.length) {
			queryParams.pageNum += 1;
			getList();
		}
	}

	// 获取任务列表
	const getList = async () => {
		const network = await checkNetwork(); // 检查网络
		if (network == "none") {
			state.offlineMode = true;
			let offline = uni.getStorageSync('offline-task-list');
			if (offline) {
        dataList.value = offline.data || [];
        state.offlineId = offline.subPlanId;
      }
			return;
		} else {
			state.offlineMode = false;
		}
		status.value = "loading";
		taskList(queryParams)
			.then((res) => {
				if (res.code == 200) {
					dataList.value =
						queryParams.pageNum == 1 ? res.rows : dataList.value.concat(res.rows || []);
					total.value = res.total;
					// 获取地图标记列表
          state.markers = dataList.value.map((item, index) => {
            return {
              id: index,
              latitude: parseFloat(item.latitude) || 0,
              longitude: parseFloat(item.longitude) || 0,
              title: item.projectName,
              iconPath: iconRed,
              width: 24,
              height: 27,
            };
          });

          state.markers.unshift({
            id: -1,
            latitude: state.latitude || 0,
            longitude: state.longitude || 0,
            title: "",
            iconPath: iconGreen,
            width: 24,
            height: 27,
          });
					reloadMap();
				}
			})
			.finally(() => {
				emit("update:refresh", false);
				uni.stopPullDownRefresh();
				status.value = total.value == dataList.value.length ? "nomore" : "loadmore";
				if (props?.onMore) emit("update:onMore", false);
			});
	};

	// 跳转任务选择
	const handleDetail = (id, projectName, cycleNo) => {
		if (state.offlineId && state.offlineId != id) {
			uni.showToast({
				title: "当前有任务未完成",
				icon: "none",
			})
			return;
		}
		uni.navigateTo({
			url: `/pages/Task/select?subPlanId=${id}&projectName=${projectName}&cycleNo=${cycleNo}`,
		});
	};

	// 生成报告
	const toReport = (id) => {
		if (state.offlineId) {
			uni.showToast({
				title: "离线模式无法操作",
				icon: "none",
			})
			return;
		}
		generateReport(id).then((res) => {
			if (res.code == 200) {
				uni.navigateTo({
					url: "/pages/Task/reportDetails?id=" + res.data,
				});
			}
		});
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";
	.task-bg {
		width: 100vw;
		height: 100vh;
		background: url("@/static/taskBg.png") no-repeat 100% 100%;
	}

	.fixbox {
		background-color: #ffffff;
		padding: 8rpx;
		margin: 0 auto;
		width: 92.2vw;
		height: calc(100vh - var(--status-bar-height) - 260rpx);
		box-sizing: border-box;
		border-radius: 20rpx;
		overflow: hidden;

		.offline-map {
			display: flex;
			align-items: center;
			justify-content: center;
			color: #6f7275;
			background-color: #f4f4f4;
			border-radius: 20rpx;
		}
	}

	.list {
		width: 90%;
		margin: 30rpx auto;
		overflow: hidden;

		.list_l {
			width: 22rpx;
			background: #87bcf5;
			height: 330rpx;
		}

		.mes {
			color: red;
		}

		.list_line {
			border-top: 2rpx solid gainsboro;
			padding-top: 14rpx;
			width: 100%;
			text-align: center;
		}
	}

	.amap-icon {
		overflow: inherit !important;
	}
</style>